﻿using System;
using System.Text;
using System.Reflection;

using Unity.Interception.PolicyInjection.MatchingRules;

namespace pri.smilly.QuickStart.Aop {
    public class ExpressionMatchRule : IMatchingRule {
        private readonly IMatcher _matcher;
        public string Expression { private set; get; }

        public ExpressionMatchRule(string expression) {
            Expression = expression;
            _matcher = new ExpressionMatcher(Expression);
        }

        public bool Matches(MethodBase method) {
            return _matcher.IsMatch(MethodSinature(method));
        }

        private string MethodSinature(MethodBase method) {
            StringBuilder builder = new StringBuilder();
            builder.Append(method.DeclaringType.Namespace).Append('.')
                .Append(method.DeclaringType.Name).Append('.')
                .Append(method.Name).Append('(');

            foreach (ParameterInfo param in method.GetParameters()) {
                builder.Append(param.ParameterType.Namespace).Append('.').Append(param.ParameterType.Name).Append(',');
            }
            if (method.GetParameters().Length > 0) builder.Remove(builder.Length - 1, 1);
            return builder.Append(')').ToString();
        }

        public override bool Equals(object obj) {
            return obj is ExpressionMatchRule && Expression.Equals((obj as ExpressionMatchRule).Expression);
        }

        public override int GetHashCode() {
            return base.GetHashCode();
        }
    }
}
